package com.jzr.netty.db1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzr.common.util.U;
import com.jzr.netty.db1.mapper.TDeviceMapper;
import com.jzr.netty.db1.model.TDevice;
import com.jzr.netty.db1.service.TDeviceService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TDeviceServiceImpl extends ServiceImpl<TDeviceMapper,TDevice> implements TDeviceService {

    @Override
    public TDevice saveByDeviceNo(TDevice record) {
        if(record == null || U.isBlank(record.getDeviceNo())){
            return null;
        }
        List<Integer> idList = baseMapper.getIdList(new QueryWrapper<TDevice>().eq(TDevice.DeviceNo_,record.getDeviceNo()));
        if(idList == null || idList.isEmpty()){
            cleanUniqueFields(record);
            baseMapper.insert(record);
        }else{
            cleanUniqueFields(record);
            record.setId(idList.get(0));
            baseMapper.updateById(record);
        }
        return record;
    }

    @Override
    public TDevice saveByRegister(TDevice record) {
        if(record == null || U.isBlank(record.getDeviceNo())){
            return null;
        }
        return saveByDeviceNo(record);
    }

    private void cleanUniqueFields(TDevice device){
        if(device == null){return;}

        UpdateWrapper<TDevice> uw = null;

        if(U.isNotBlank(device.getDeviceIp())) {
            uw = new UpdateWrapper<>();
            uw.set(TDevice.DeviceIp_, null)
                    .eq(TDevice.DeviceIp_, device.getDeviceIp());
            baseMapper.update(null, uw);
        }

        if(U.isNotBlank(device.getRegisterBed())){
            uw = new UpdateWrapper<>();
            uw.set(TDevice.RegisterBed_, null)
                    .eq(TDevice.RegisterBed_, device.getRegisterBed());
            baseMapper.update(null, uw);
        }

    }
}
